﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EMC;
using System.Net.Sockets;
using System.IO;
using System.Reflection;

namespace FileServer
{
    public class UserHandler
    {
        private Socket clientSocket;
        private UserManagement userman;

        public UserHandler(Socket clientSock)//, UserManagement userMana)
        {
            clientSocket = clientSock;
            //userman = userMana;
            string dbConfigFile = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Program)).CodeBase) + @"/db_settings.xml";
            databaseConfiguration config = new databaseConfiguration(dbConfigFile);
            userman = new UserManagement(config);

        }

        public string handleUser(string[] message)
        {
            string ret = null;
            System.Diagnostics.Debug.WriteLine(message[2]);
            if (message[2] == "LOGIN")
            {
                login(message[3],message[4]);
                //ret = "LOGIN";
            }
            else if (message[2] == "GET")
            {
                ret = "GET";

            }
            else if (message[2] == "CREATE")
            {
                ret = "CREATE";
                foreach (string i in message)
                {
                    System.Diagnostics.Debug.WriteLine(i);
                }
                userman.adduser(message[3], message[4], message[5], message[6]);
            }
            else if (message[2] == "DELETE")
            {
                ret = "DELETE";
            }
            else
            {
                ret = "404 not found";
            }

            return ret;
        }



        private string login(string user, string pass)
        {
            string ret = null;
            System.Diagnostics.Debug.WriteLine(userman.authenticateUser(user, pass));

            //UserHandler userHandler = new UserHandler(clientSock, userman);
            //userHandler.handleUser(message);
            //string username = message[2];
            //string password = message[3];

            ////System.Diagnostics.Debug.WriteLine("\nAuth user: " + userman.authenticateUser(username, password));

            //if (userman.authenticateUser(username, password))
            //{
            //    ret = "$CLIENT,LOGIN,OK,";
            //}
            //else
            //{
            //    ret = "$CLIENT,LOGIN,BAD,";
            //}
            return ret;
        }
    }
}
